<template>
	<simple-layout
		ref="simpleLayoutRef"
		class="simple-layout-common-box"
		:isUseCheck="false"
		:isDisabled="true"
		:inputSearch="inputSearch"
		@toSearch="onSearch"
		@toBlur="onBlur"
	>
		<template slot="content">
			<top-bottom-layout :is-show-down="isShowDown">
				<template slot="top">
					<transfer-tree
						:checkable="checkable"
						:checkedList="checkedList"
						:defaultExpandedKeys="defaultExpandedKeys"
						:defaultSelected="defaultSelected"
						:treeData="treeData"
						:isUseDefaultIcon="false"
						iconType="cap-icon-alternative-external-un"
						@toCheckedNode="onJoinCheckedNode"
						@toSelectNode="onJoinSelectNode"
					></transfer-tree>
				</template>
				<template slot="middle"></template>
				<template slot="bottom">
					<scrollList
						panel="JoinOrganization"
						:command="searchValue ? 'doSearch' : 'memberList'"
						ref="scrollList"
						:firstLoadSearch="firstLoadSearch"
						:showOtherProp="true"
						:otherProps="memberOtherProps"
					></scrollList>
				</template>
			</top-bottom-layout>
		</template>
	</simple-layout>
</template>

<script>
import SimpleLayout from '@/components/simpleLayout.vue';
import topBottomLayout from '@/components/topBottomLayout.vue';
import transferTree from '@/components/transferTree.vue';
import scrollList from '@/components/scrollList';
import {EntityTypes} from '@/utils/orgConstants';
import {mapActions, mapState} from 'vuex';

import {getPanelData} from '@/api/modules/SelectOrgApi';
import {CheckUtils} from '@/utils/checkUtils';
import {MaskAsync} from '@/utils/Mask.js';

import {ACTION_REMOVE_ENTITY} from '@/store/actionTypes';

export default {
	name: 'JoinOrganization',
	components: {
		SimpleLayout,
		topBottomLayout,
		transferTree,
		scrollList
	},
	inject: ['app'],
	data() {
		return {
			searchValue: '',

			treeData: [],
			checkable: true,
			defaultExpandedKeys: [],
			defaultSelected: [],
			canSelectMember: true,
			isShowDown: true,
			accountIds: [],

			firstLoadSearch: false,
			memberOtherProps: [],

			unitId: '',
			units: []
		};
	},
	computed: {
		...mapState('selectData', ['selectedEntityMap']),
		checkedList() {
			let list = [...JSON.parse(JSON.stringify(this.accountIds))];
			return list;
		},
		orgSelect() {
			return this.app().orgSelect;
		},
		isSelectAccontDepartment() {
			let isSelectAccount = this.orgSelect.selectType.includes(EntityTypes.Account);
			let isSelectDeparment = this.orgSelect.selectType.includes(EntityTypes.Department);
			if (isSelectAccount || isSelectDeparment) {
				return true;
			} else {
				return false;
			}
		},
		inputSearch() {
			let resObj = {
				disabled: false,
				placeText: ''
			};
			let isSelectMember = this.orgSelect.selectType.includes(EntityTypes.Member);
			if (this.isSelectAccontDepartment && isSelectMember) {
				resObj.placeText = this.$i18n('selectPeople.input',`${this.$i18n('org.JoinOrganization.label')}/${this.$i18n('org.member.label')}`);
				return resObj
			}
			if (this.isSelectAccontDepartment) {
				resObj.placeText = this.$i18n('selectPeople.input',`${this.$i18n('org.JoinOrganization.label')}`);
				return resObj
			}
			if (isSelectMember) {
				resObj.placeText = this.$i18n('selectPeople.input',`${this.$i18n('org.member.label')}`);
				return resObj
			}
		}
	},
	watch: {
		selectedEntityMap: {
			deep: true,
			handler(val) {
				this.onSelectMap(val);
			}
		}
	},
	methods: {
		...mapActions('selectData', [ACTION_REMOVE_ENTITY]),
		async onGetPanelData(data = {}) {
			let {
				onlyCurrentDepartment,
				isNeedCheckLevelScope,
				showDepartmentsOfTree,
				showDepartmentsNoChildrenOfTree,
				showExternalType
			} = this.orgSelect;
			let params = {
				command: 'unitTree',
				panel: 'JoinOrganization',
				arguments: {
					onlyCurrentDepartment,
					isNeedCheckLevelScope,
					showDepartmentsOfTree,
					showDepartmentsNoChildrenOfTree,
					showExternalType,
					...data
				}
			};
			let res = await getPanelData(params);
			if (res.code === 0) {
				this.treeData = JSON.parse(JSON.stringify(res.data));
				if (this.treeData.length) {
					let treeFirstNodeId = this.treeData[0].id;
					this.$set(this.defaultExpandedKeys, 0, treeFirstNodeId);
					this.$set(this.defaultSelected, 0, treeFirstNodeId);
					this.unitId = treeFirstNodeId;
				}
			}
		},
		onSearchData(data) {
			this.$nextTick(()=>{
				this.$refs.scrollList.search(data);
				this.isShowDown = false;
			})

		},
		onSearch(val) {
			console.log('val',val);
			this.searchValue = val;
			let { isNeedCheckLevelScope, accessFileSecretLevel, showExternalType, selectType } = this.orgSelect;
			let defaultSearchType = [EntityTypes.Department, EntityTypes.Member];
			let searchType = defaultSearchType.filter(x => selectType.includes(x)).join(',');
			this.unitId = this.unitId.split(',')[0];
			this.$nextTick(() => {
				this.onSearchData({
					keyword: val,
					isNeedCheckLevelScope,
					accessFileSecretLevel,
					showExternalType,
					unitId: this.unitId,
					searchType
				});
			});
		},
		onBlur(val) {
			this.searchValue = val;
		},
		onJoinCheckedNode(data, nodeEl) {
			// 当前节点是否被选中
			let currentNodeState = nodeEl.checked;
			// 取消选择
			if (currentNodeState) {
				this[ACTION_REMOVE_ENTITY]({
					entities: data.checkeds
				});
				return;
			}
			this.onCheckScopeStatus(data.checkeds);
		},
		onJoinSelectNode(data) {
			console.log('data', data);
			if (!this.canSelectMember) {
				return;
			}

			if (!data.selected.length) {
				return;
			}
			this.searchValue = ''
			let { isNeedCheckLevelScope, accessFileSecretLevel } = this.orgSelect;

			// this.unitId = data.id;
			let type = data.selected[0].type;
			this.unitId = this.onGetUnits(data, type);
			this.onSearchData({
				unitId: data.id,
				isNeedCheckLevelScope,
				accessFileSecretLevel
			});
		},
		@MaskAsync
		async onCheckScopeStatus(nodes) {
			let entity = nodes[0];
			let notIncludeSubDept = [];
			let checkContext = {
				currentPanel: 'JoinOrganization',
				notIncludeSubDept
			};
			let result = await CheckUtils.doCheckEntity(entity, checkContext);
			if (!result) {
				return;
			}
			this.selectDataToRight(nodes);
		},
		onSelectMap(val) {
			let pathKeys = val && Object.keys(val);
			if (pathKeys && pathKeys.length) {
				this.onTreeNodeAccount(val);
			} else {
				this.accountIds = [];
			}
		},
		onTreeNodeAccount(data) {
			this.accountIds = [];
			let typeIds = Object.keys(data);
			for (let item of typeIds) {
				if (
					item.indexOf('Account') !== -1 ||
					item.indexOf('Department') !== -1
				) {
					this.accountIds.push(item.split('|')[1]);
				}
			}
		},
		/**
		 *  场景：搜索部门、人员时传需要回传单位id、部门id
		 *  1: 如果是单位，传单位id
		 *  2: 如果是部门，传当前部门id和部门下的所有子部门id
		 *  输入： @params (Object) node 当前节点数据
		 *         @params (String) type 当前节点类型
		 *  输出：@params (String) unitsString  当前节点返回的字符串（"id1,id2,id3,id4"）
		 *
		 */
		// --开始处理
		onGetUnits(node, type) {
			this.units = [];
			let unitsString = '';
			let activeNodeId = node.id;
			this.units.push(activeNodeId);
			// 单位：传当前部门，子部门所有id
			if (type === 'Department') {
				this.onSureActiveId(this.treeData, activeNodeId);
			}
			unitsString = this.units.join(',');
			return unitsString;
		},
		onSureActiveId(nodes, activeId) {
			for (let i = 0; i < nodes.length; i++) {
				if (
					nodes[i].id === activeId &&
					nodes[i].children &&
					nodes[i].children.length > 0
				) {
					this.onRecursionUnitsId(nodes[i].children);
				} else if (nodes[i].children && nodes[i].children.length > 0) {
					this.onSureActiveId(nodes[i].children, activeId);
				}
			}
		},
		onRecursionUnitsId(nodes) {
			for (let i = 0; i < nodes.length; i++) {
				this.units.push(nodes[i].id);
				if (nodes[i].children && nodes[i].children.length > 0) {
					this.onRecursionUnitsId(nodes[i].children);
				}
			}
		},
		// --结束处理
		onChangeAccount(data) {
			this.$refs.simpleLayoutRef.onChangeAccount(data);
		}
	},
	created() {
		this.canSelectMember = this.orgSelect.selectType.includes(EntityTypes.Member);
		this.checkable = this.orgSelect.selectType.includes(EntityTypes.Department);
		this.onGetPanelData({
			accountId: this.orgSelect.defaultAccountId
		});
	},
	mounted() {
		this.onSelectMap(this.selectMap);
	}
};
</script>

<style scoped lang="scss">
</style>
